using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace SharpFastCGI
{
	public class SimpleSocketServer : Server
	{
		private Socket mSocket;
		private int mBacklog;
		private IPEndPoint mEndPoint;
		
		public IPEndPoint EndPoint
		{
			get { return mEndPoint; }
			set { mEndPoint = value; }
		}
		
		public int Backlog
		{
			get { return mBacklog; }
			set { mBacklog = value; }
		}
		
		public SimpleSocketServer()
		{
			mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			mBacklog = 100;
		}
		
		public override void Start()
		{
			base.Start();
			s.Bind(mEndPoint);
			s.Listen(mBacklog);
		}
		
		public override void Stop()
		{
			if(!IsRunning) throw new InvalidOperationException();
			mSocket.Close();
			base.Stop();
		}
		
		protected override int GetMaxSimultaneousConnections()
		{
			return mBacklog;
		}
		
		protected override Stream Accept()
		{
			try
			{
				return new NetworkStream(mSocket.Accept());
			}
			catch(SocketException) // server stopped
			{
				return null;
			}
		}
		
		protected override string[] TypicalEnvironmentVariables()
		{
			return new string[] {
				"SCRIPT_FILENAME",
				"QUERY_STRING",
				"REQUEST_METHOD",
				"CONTENT_TYPE",
				"CONTENT_LENGTH",
				"GATEWAY_INTERFACE",
				"SERVER_SOFTWARE",
				"SCRIPT_NAME",
				"REQUEST_URI",
				"DOCUMENT_URI",
				"DOCUMENT_ROOT",
				"SERVER_PROTOCOL",
				"REMOTE_ADDR",
				"REMOTE_PORT",
				"SERVER_ADDR",
				"SERVER_PORT",
				"SERVER_NAME"
			};
		}
	}
}
